import React, { useState, useEffect } from "react";
import { Button, Image, Popconfirm, Space, Tag } from "antd";
import MyTemplate1 from "../../shared/myTemplate1";
import useCloseLoadingOnMount from "../../../utils/hook/useCloseLoadingOnMount";
import { useNavigate } from "react-router-dom";
import goodsApi from "../../../apis/goodsApi";
import {
  getImagePath,
  getImagePath2,
  promptResult2,
} from "../../../utils/common";
import { debounceAsync } from "../../../utils/common/debounce";

const GoodManage = () => {
  useCloseLoadingOnMount();
  const [dataSource, setDataSource] = useState([]); // 表格的数据
  const [loading, setLoading] = useState(false); // 表格的加载状态
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    key: "",
    total: 0,
  }); // 分页
  const [flag, setFlag] = useState(false);
  const navigate = useNavigate();

  // 模拟API请求
  const fetchProducts = async () => {
    setLoading(true);
    const res = await goodsApi.getGoodsPagination({
      page: pagination.current,
      limit: pagination.pageSize,
      key: pagination.key,
    });
    if (res.status >= 0) {
      setDataSource(res.data.data);
    }
    setPagination({ ...pagination, total: res.data.total });
    setLoading(false);
  };

  // 监听分页对象属性变化，当变化时进行分页
  useEffect(() => {
    fetchProducts();
  }, [pagination.current]);

  useEffect(() => {
    if (flag) {
      console.log("执行了");
      if (pagination.current != 1) {
        setPagination({ ...pagination, current: 1 });
      } else {
        fetchProducts();
      }
    }
    setFlag(true);
  }, [pagination.pageSize, pagination.key]);

  // 监听搜索
  const handleSearch = debounceAsync((e) => {
    setPagination({ ...pagination, key: e.target.value });
  }, 1000);

  // 表格的列属性
  const columns = [
    {
      title: "封面图片",
      dataIndex: "photo",
      key: "photo",
      render: (text, row) => {
        var images = text.split(",");
        if (images.length > 0) {
          return (
            <Image
              src={getImagePath2(row.id, images[0])}
              height={"60px"}
            ></Image>
          );
        } else {
          return "-";
        }
      },
    },
    {
      title: "商品名称",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "供应商",
      dataIndex: "supplierShopName",
      key: "supplierShopName",
    },
    {
      title: "商品类别",
      dataIndex: "goodTypeName",
      key: "goodTypeName",
    },
    {
      title: "商品价格",
      dataIndex: "price",
      key: "price",
      render: (price) => `¥${price.toFixed(2)}`,
    },
    {
      title: "产品描述",
      dataIndex: "description",
      key: "description",
    },
    {
      title: "详情图片",
      dataIndex: "detailImages",
      key: "detailImages",
      render: (text, row) => {
        var images = text.split(",");
        if (images.length > 0) {
          return (
            <Image
              src={getImagePath2(row.id, images[0])}
              height={"60px"}
            ></Image>
          );
        } else {
          return "-";
        }
      },
    },
    {
      title: "商品规格",
      dataIndex: "specs",
      key: "specs",
    },
    {
      title: "是否直营",
      dataIndex: "isDirectly",
      key: "isDirectly",
      render: (isDirectly) => (
        <Tag color={isDirectly === 1 ? "green" : "red"}>
          {isDirectly === 1 ? "是" : "否"}
        </Tag>
      ),
    },
    {
      title: "是否上架",
      dataIndex: "isShelve",
      key: "isShelve",
      render: (isShelve) => (
        <Tag color={isShelve === 1 ? "green" : "red"}>
          {isShelve === 1 ? "已上架" : "已下架"}
        </Tag>
      ),
    },
    {
      title: "库存",
      dataIndex: "inventory",
      key: "inventory",
    },
    {
      title: "生产日期",
      dataIndex: "birthdayStr",
      key: "birthdayStr",
    },
    {
      title: "保质期",
      dataIndex: "expiryday",
      key: "expiryday",
    },
    {
      title: "是否促销",
      dataIndex: "isPromote",
      key: "isPromote",
      render: (isPromote) => (
        <Tag color={isPromote === 1 ? "green" : "red"}>
          {isPromote === 1 ? "是" : "否"}
        </Tag>
      ),
    },
    {
      title: "置顶级别",
      dataIndex: "topLevel",
      key: "topLevel",
    },
    {
      title: "创建时间",
      dataIndex: "createTimeStr",
      key: "createTimeStr",
    },
    {
      title: "修改时间",
      dataIndex: "updateTimeStr",
      key: "updateTimeStr",
    },
    {
      title: "操作",
      key: "action",
      fixed: "right",
      render: (_, record) => (
        <Space size="middle">
          <Button
            color="geekblue"
            variant="filled"
            onClick={() => handleDetail(record.id)}
          >
            详情
          </Button>
          <Popconfirm
            title="删除商品"
            description={`你确定要删除"${record.name}"吗?`}
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button color="red" variant="filled">
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const handleDelete = async (id) => {
    await promptResult2(goodsApi.deleteGoods(id), () => {}, fetchProducts);
  };

  const handleDetail = (id) => {
    navigate("detail/" + id);
  };

  return (
    <MyTemplate1
      searchProps={{
        placeholder: "搜索商品名称",
        onChange: handleSearch,
      }}
      addButtonProps={{
        text: "新增商品",
        onClick: () => navigate("/good/add"),
      }}
      columns={columns}
      dataSource={dataSource}
      loading={loading}
      pagination={pagination}
      onPageChange={(page, pageSize) => {
        setPagination({
          ...pagination,
          current: page,
          pageSize,
        });
      }}
    />
  );
};

export default GoodManage;
